package cn.yzking.studentmanagement;

import androidx.appcompat.app.AppCompatActivity;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.ArrayAdapter;

import com.google.android.material.datepicker.MaterialDatePicker;
import com.google.android.material.dialog.MaterialAlertDialogBuilder;

import java.text.SimpleDateFormat;
import java.util.Locale;

import cn.yzking.studentmanagement.databinding.ActivityAddStudentBinding;
import cn.yzking.studentmanagement.utils.MyDBHelper;

public class AddStudentActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ActivityAddStudentBinding binding = ActivityAddStudentBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());

        setResult(Activity.RESULT_CANCELED);

        ArrayAdapter<String> adapter = new ArrayAdapter<>(this, R.layout.item_sex, new String[]{"男", "女", "保密"});
        binding.tvSex.setAdapter(adapter);

        MaterialDatePicker<Long> datePicker = MaterialDatePicker.Builder.datePicker()
                .setTitleText("选择出生日期")
                .setSelection(MaterialDatePicker.todayInUtcMilliseconds())
                .setInputMode(MaterialDatePicker.INPUT_MODE_TEXT)
                .build();
        datePicker.addOnPositiveButtonClickListener(selection -> {
            // 时间戳转换
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd", Locale.SIMPLIFIED_CHINESE);
            String dateString = formatter.format(selection);
            binding.etBirthday.setText(dateString);
        });

        binding.etBirthday.setOnClickListener(v -> datePicker.show(getSupportFragmentManager(), "tag"));

        binding.buttonAdd.setOnClickListener(v -> {
            MyDBHelper helper = new MyDBHelper(this);
            String name = binding.etName.getText().toString();
            if (helper.AddStudent(binding.etId.getText().toString(), name, binding.etPhone.getText().toString(), binding.tvSex.getText().toString(), binding.etBirthday.getText().toString())) {
                Intent intent = new Intent();
                setResult(Activity.RESULT_OK, intent);
                new MaterialAlertDialogBuilder(this)
                        .setIcon(R.drawable.ic_success)
                        .setTitle("添加成功")
                        .setMessage("学生[" + name + "]注册成功!")
                        .setPositiveButton("OK", null)
                        .setOnDismissListener(dialog -> finish())
                        .show();
            } else {
                new MaterialAlertDialogBuilder(this)
                        .setIcon(R.drawable.ic_error)
                        .setTitle("注册失败")
                        .setMessage("学生[" + name + "]注册失败!")
                        .setNegativeButton("确定", null)
                        .show();
            }
        });
    }
}